package cn.itcast.bos.web.action.system;
	

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.IUserService;
import cn.itcast.bos.web.action.common.BaseAction;

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class UserAction extends BaseAction<User>{
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private IUserService UserService;

	@Action(value="user_login", results = {@Result(name="login", location="login.html", type="redirect"),
			@Result(name="success", type="redirect", location="index.html")})
	public String login() {
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
		try {
			subject.login(token);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return LOGIN;
		}
	}
	
	//退出 user_logout
	@Action(value="user_logout", results={@Result(name="success", 
			type="redirect", location="login.html")})
	public String logout() {
		//获取subject
		Subject subject = SecurityUtils.getSubject();
		
		//退出
		subject.logout();
		
		return SUCCESS;
	}
	
	//用户管理数据显示user_list
	@Action(value="user_list", results={@Result(name="success", 
			type="json")})
	public String list() {
		List<User> userList = UserService.findAll();
		ActionContext.getContext().getValueStack().push(userList);
		return SUCCESS;
	}
	
	//属性驱动
	private String[] roleIds;

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action(value="user_save", results={@Result(name="success", 
			type="redirect", location="pages/system/userlist.html")})
	public String userSave() {
		UserService.saveUser(model, roleIds);
		
		return SUCCESS;
	}
}
